<template>
  <div style="padding: 8px; margin: 8px">
    <el-card>
      <el-steps :active="1" simple>
        <el-step title="提交变更" icon="el-icon-edit"></el-step>
        <el-step title="审核" icon="el-icon-s-claim"></el-step>
        <el-step title="执行" icon="el-icon-s-check"></el-step>
      </el-steps>
    </el-card>

    <el-row :gutter="8" style="padding-top: 8px">
      <el-col :span="6">
        <el-card>
          <el-row>
            <el-form ref="form" :model="newOrderForm" label-position="left" :rules="orderFormRules" label-width="90px">
              <el-form-item label="工单类型:" prop="orderType" size="small">
                <el-input v-model="newOrderForm.orderType" type="text" readonly></el-input>
              </el-form-item>
              <el-form-item label="DB类型:" prop="dbType" size="small">
                <el-input v-model="newOrderForm.dbType" type="text" readonly></el-input>
              </el-form-item>
              <el-form-item label="集群(租户):" prop="tenantId" size="small">
                <el-select
                  v-model="newOrderForm.tenantId"
                  placeholder="请选择"
                  style="display: block"
                  :popper-append-to-body="false"
                  popper-class="options-content"
                  @change="changeDb"
                >
                  <el-option v-for="item in tenantsList" :key="item.id" :label="`${item.name}(${item.cluster.name})`" :value="item.id">
                    <span style="float: left; font-weight: bolder">{{ item.name }}</span>
                    <span style="float: right; color: #e6a23c; font-size: 13px; padding-right: 5px">集群:{{ item.cluster.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="库名称:" prop="dbDatabase" size="small">
                <el-select
                  v-model="newOrderForm.dbDatabase"
                  placeholder="请选择"
                  :popper-append-to-body="false"
                  popper-class="options-content"
                  style="display: block"
                  :clearable="true"
                  @change="changeDbDatabase"
                >
                  <el-option v-for="item in dbDatabaseList" :key="item.id" :label="item.dbName" :value="item.dbNameCopy">
                    {{ item.dbName }}
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="表名:" prop="dbTable" size="small">
                <el-select v-model="newOrderForm.dbTable" placeholder="请选择" style="display: block" :popper-append-to-body="false" popper-class="options-content">
                  <el-option v-for="item in dbTableList" :key="item.id" :label="item.name" :value="item.id">
                    {{ item.name }}
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="工单说明:" prop="description" size="small">
                <el-input v-model="newOrderForm.description" :autosize="{ minRows: 4, maxRows: 10 }" placeholder="请输入描述信息" type="textarea"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button v-if="!codeChange && checkSuccess" :loading="submitLoading" size="small" type="success" @click="ok('form')">提交</el-button>
                <el-button v-else size="small" type="primary" @click="sqlTest('form')">SQL审核</el-button>
                <!-- <el-button size="small" @click="cancel">获取表结构</el-button> -->
              </el-form-item>
            </el-form>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="18">
        <Tabs v-model="activeName" style="background-color: white">
          <TabPane name="sql" label="SQL">
            <el-card>
              <div>
                <el-row>
                  <el-col>
                    <Button type="success" size="small" @click="formatSql">格式化SQL</Button>
                    <!-- <Button size="small" type="primary" @click="test()">审核SQL</Button> -->
                  </el-col>
                </el-row>
              </div>
              <br />
              <div style="margin: -10px">
                <codemirror ref="originalSql" v-model="newOrderForm.sqls" :options="cmOptions" class="CodeMirror" @changes="onCmCodeChanges"></codemirror>
              </div>
            </el-card>
            <sql-check :sql-check-datas="sqlCheckDatas"></sql-check>
            <md-view :sql-suggest="sqlSuggest"></md-view>
          </TabPane>
          <!-- <TabPane label="表结构详情" name="tableDetail">表结构详情</TabPane>
          <TabPane label="索引详情" name="indexDetail">索引详情</TabPane> -->
        </Tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { codemirror } from 'vue-codemirror'
import 'codemirror/mode/sql/sql.js'
import { format } from 'sql-formatter'
import 'codemirror/addon/edit/matchbrackets.js'
// 引入代码自动提示插件
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/sql-hint.js'
import 'codemirror/addon/hint/show-hint.js'
import 'codemirror/addon/lint/lint.js'
import 'codemirror/addon/lint/lint.css'
import SqlCheck from '@/views/ticket/order/components/SqlCheck/index'
import { createTicketOrder, goinceptionCheckTicketOrder } from '@/api/ticket/order'
import { createTicketLog } from '@/api/ticket/log'
import { errorNotify } from '@/libs/util'
import { snakeCaseObject } from '@/libs/object'
import { getObTenantList, getObTenant } from '@/api/ob/tenant'
import { getObTableList } from '@/api/ob/table'
import MdView from '@/components/MdView/index'
export default {
  name: 'Apply',
  components: { codemirror, SqlCheck, MdView },
  props: {
    orderType: {
      type: String,
      require: true,
      default: ''
    }
  },
  data() {
    return {
      sqlSuggest: '',
      submitLoading: false,
      tenantsList: [],
      dbDatabaseList: [],
      dbTableList: [],
      newOrderForm: {
        orderType: this.orderType,
        dbType: 'OceanBase',
        sqls: '',
        dbDatabase: '',
        dbTable: '',
        tenantId: ''
      },
      activeName: 'sql',
      codeChange: true,
      checkSuccess: false,
      sqlCheckDatas: [],
      orderFormRules: {
        dbType: [{ trigger: 'blur', required: true, message: 'DB类型不能为空' }],
        orderType: [{ trigger: 'blur', required: true, message: '工单类型不能为空' }],
        tenantId: [{ trigger: 'blur', required: true, message: 'DB集群/租户必选' }],
        dbDatabase: [{ trigger: 'blur', required: true, message: '尚未选择操作数据库' }],
        // dbTable: [{ trigger: 'blur', required: true, message: '尚未选择操作表' }],
        description: [{ trigger: 'blur', required: true, message: '描述信息不能为空' }]
      },
      cmOptions: {
        // codemirror options
        tabSize: 2,
        indentUnit: 4,
        mode: 'text/x-mariadb',
        matchBrackets: true,
        theme: 'default',
        lineNumbers: true,
        line: true,
        styleActiveLine: true,
        readOnly: false,
        lineWrapping: true,
        lint: true, // 检查格式
        spellcheck: true, // 拼写检查
        hintOptions: {
          completeSingle: false,
          tables: {}
        }
      }
    }
  },
  mounted() {
    this.$refs.originalSql.codemirror.on('inputRead', (originalSql) => {
      originalSql.showHint()
    })
    this.getObTenantList()
  },
  methods: {
    formatSql() {
      /* （sql编辑器内容绑定content参数） 将sql内容进行格式后放入编辑器中*/
      this.newOrderForm.sqls = format(this.newOrderForm.sqls)
    },
    onCmCodeChanges() {
      this.codeChange = true
    },
    setCheckSuccess(val) {
      this.checkSuccess = val['status']
    },
    changeDb(event) {
      this.dbDatabaseList = []
      this.newOrderForm.dbDatabase = ''
      this.getObTenant(event)
    },
    changeDbDatabase(event) {
      this.dbTableList = []
      this.newOrderForm.dbTable = ''
      this.getObTableList(event)
    },
    async createTicketLog(params) {
      try {
        await createTicketLog(snakeCaseObject(params))
      } catch (e) {
        errorNotify(e)
      }
    },
    async createTicketOrder() {
      this.submitLoading = true
      const params = this.newOrderForm
      try {
        const { data } = await createTicketOrder(snakeCaseObject(params))
        const logParams = {
          orderId: data.id,
          type: 'submit',
          result: this.sqlCheckDatas
        }
        this.createTicketLog(logParams)
        this.$router.push('/ticket/order')
      } catch (e) {
        errorNotify(e)
      } finally {
        this.submitLoading = false
      }
    },
    async getObTableList(databaseName) {
      try {
        const { data } = await getObTableList(this.newOrderForm.tenantId, databaseName)

        const tmpTableList = []
        data.map((item) => {
          tmpTableList.push({ id: item, name: item })
        })
        this.dbTableList = tmpTableList
        const optionTables = { [databaseName]: data }
        this.cmOptions.hintOptions.tables = optionTables
      } catch (e) {
        errorNotify(e)
      }
    },
    async getObTenantList() {
      try {
        const { data } = await getObTenantList()
        this.tenantsList = data
      } catch (e) {
        errorNotify(e)
      }
    },
    async getObTenant(tenantId) {
      try {
        const { data } = await getObTenant(tenantId)
        const tmpDatabase = []
        data.databases.map((item) => {
          tmpDatabase.push({ dbName: item.dbName, id: item.id, dbNameCopy: item.dbName })
        })
        this.dbDatabaseList = tmpDatabase
      } catch (e) {
        errorNotify(e)
      }
    },
    sqlTest(formName) {
      this.onCmCodeChanges()
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.newOrderForm.sqls === '') {
            this.$Notice.error({ title: 'Sql不能为空' })
          } else {
            this.sqlCheckDatas = []
            this.goinceptionCheckTicketOrder()
            this.codeChange = false
          }
        } else {
          return false
        }
      })
    },
    ok(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.createTicketOrder()
        } else {
          return false
        }
      })
    },
    cancel() {
      console.log('cancel')
    },
    async goinceptionCheckTicketOrder() {
      try {
        const { data } = await goinceptionCheckTicketOrder(snakeCaseObject(this.newOrderForm))
        this.sqlCheckDatas = data
        const checkResult = []
        data.map((item) => {
          checkResult.push(item.errorLevel)
        })
        console.log(checkResult)
        // 如果结果中包含2 也就是严重级别，则不允许提交。
        if (checkResult.includes(2)) {
          this.checkSuccess = false
        } else {
          this.checkSuccess = true
        }
      } catch (e) {
        errorNotify(e)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.CodeMirror {
  height: auto;
}
.CodeMirror-scroll {
  height: auto;
  overflow-y: auto;
  overflow-x: auto;
}
</style>
